import React, { Component } from 'react';
import { Row, Col, Card, Select, Button, Form, message, List, Skeleton, Popconfirm } from 'antd';
const { Option } = Select;
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import styles from './index.less';
import CreateUpdateForm from './components/CreateUpdateForm';
import { pagination, dateFormat } from '@/utils/utils';
import router from 'umi/router';

@connect(({ jobManage }) => ({
  listUserJobReport: jobManage.listUserJobReport
}))

class jobReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      createModalVisible: false,
      updateModalVisible: false,
      updateFormData: {},
      taskDescription: null,
      setPagination: {
        ...pagination
      }
    };
  }

  componentDidMount() {
    this.searchListUserJobReport()
  }

  searchListUserJobReport = () => {
    const { userJobId } = this.props.location.state
    const { setPagination } = this.state
    const requestParams = {
      page: setPagination.current,
      size: setPagination.pageSize,
      userJobId
    }
    this.props.dispatch({
      type: 'jobManage/searchListUserJobReport',
      payload: requestParams,
    })
  }

  handleCreatModalVisible = (flag) => {
    const { name } = this.props.location.state
    this.setState({
      createModalVisible: flag,
      updateFormData: {
        name
      }
    });
  }

  handleUpdateModalVisible = (flag, values) => {
    const { name } = this.props.location.state
    this.setState({
      updateModalVisible: flag,
      updateFormData: {
        ...values,
        name
      }
    });
  }

  refreshTable = async () => {
    console.log('refreshTable')
  }

  /**
 * 添加节点
 * @param fields
 */
  handleAdd = async fields => {
    const { userJobId } = this.props.location.state
    const hide = message.loading('正在添加');
    const requestParams = {
      ...fields,
      userJobId,
    }
    try {
      await this.props.dispatch({
        type: 'jobManage/addUserJobReport',
        payload: requestParams,
      })
      hide();
      this.searchListUserJobReport() //重载刷新列表
      this.handleCreatModalVisible(false)
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  /**
   * 编辑企业任务承揽方进度报告
   * @param fields
   */
  handleUpdate = async fields => {
    const hide = message.loading('正在配置');
    try {
      await this.props.dispatch({
        type: 'jobManage/editUserJobReport',
        payload: fields,
      })
      hide();
      this.searchListUserJobReport() //重载刷新列表
      this.handleUpdateModalVisible(false)
      message.success('编辑成功');
      return true;
    } catch (error) {
      hide();
      message.error('编辑失败请重试！');
      return false;
    }
  };

  /**
   *  删除节点
   * @param selectedRows
   */
  handleRemove = async selectedRows => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await this.props.dispatch({
        type: 'jobManage/deleteUserJobReport',
        payload: { userJobReportId: selectedRows.id },
      })
      hide();
      message.success('删除成功，即将刷新');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  // 页码切换
  handlePageChange = current => {
    const { setPagination } = this.state
    this.setState({
      setPagination: {
        ...setPagination,
        current
      }
    })
  };

  // 每页/条 切换
  handleSizeChange = (current, pageSize) => {
    const { setPagination } = this.state
    this.setState({
      setPagination: {
        ...setPagination,
        current, pageSize
      }
    })
  };

  render() {
    const { listUserJobReport } = this.props
    const {
      createModalVisible,
      updateModalVisible,
      updateFormData,
      setPagination,
      taskDescription
    } = this.state

    const pagination = {
      ...setPagination,
      // total: data.length,
      showTotal: count => `总共 ${count} 条`,
      onShowSizeChange: this.handleSizeChange,
      onChange: this.handlePageChange,
    };
    return (
      <PageHeaderWrapper className={styles.userContainer}>
        <Button type="link" icon="step-backward"
          onClick={this.refreshTable}
          style={{ marginBottom: 4 }}
          onClick={() => router.push('/taskManagement/userManage')}>返回
        </Button>
        <Card bordered={false} className="marginB24">
          <Row type="flex" justify="space-between">
            <Col style={{ lineHeight: '32px' }}>
              承揽方：{this.props.location.state.name}
            </Col>
            <Col>
              <Button type="primary" icon="plus" onClick={() => this.handleCreatModalVisible(true)}>添加进度汇报</Button>
            </Col>
          </Row>
        </Card>

        <Card bordered={false}>
          <List
            className="demo-loadmore-list"
            // loading={initLoading}
            itemLayout="vertical"
            // loadMore={loadMore}
            dataSource={listUserJobReport.content}
            renderItem={item => (
              <List.Item
                actions={
                  [<a onClick={() => this.handleUpdateModalVisible(true, item)} key="list-loadmore-edit">编辑</a>,
                  <Popconfirm
                    title={`确认删除该条进度汇报？`}
                    onConfirm={async () => {
                      await this.handleRemove(item);
                    }}
                    okText="确定"
                    cancelText="取消"
                  >
                    <a key="list-loadmore-more">删除</a>
                  </Popconfirm>]
                }
              >
                <Skeleton avatar title={false} loading={item.loading} active>
                  <List.Item.Meta
                    title={<a>{dateFormat(item.createTime)}</a>}
                    description={item.description}
                  />
                  <div className={styles.reportAnnexList}>
                    {item.reportAnnexList.map(v => (
                      <div style={{ backgroundImage: `url(${v.annexUrl})` }} 
                        className={styles.annexUrl} 
                        key={v.id} 
                        onClick={() => window.open(v.annexUrl)}></div>
                      // <img width={272} height={168} src={v.annexUrl} alt={v.annexTypeDesc} />
                    ))}
                  </div>
                </Skeleton>
              </List.Item>
            )}
          />
        </Card>

        <CreateUpdateForm
          onSubmit={value => this.handleAdd(value)}
          onCancel={() => this.handleCreatModalVisible(false)}
          modalVisible={createModalVisible}
          formVals={updateFormData}
        />

        <CreateUpdateForm
          onSubmit={value => this.handleUpdate(value)}
          onCancel={this.handleUpdateModalVisible}
          modalVisible={updateModalVisible}
          formVals={updateFormData}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Form.create()(jobReport)
